//
//  TomatoClockWidget.swift
//  TomatoClockWidget
//
//  Created by DaleGuo on 2023/10/31.
//

import SwiftUI
import WidgetKit

struct Provider: TimelineProvider {
    @AppStorage("tomatoDate", store: UserDefaults(suiteName: "group.com.dale.tomato_clock")) var tomatoDate: Date = Date().addingTimeInterval(25*60)

    @AppStorage("is_starting", store: UserDefaults(suiteName: "group.com.dale.tomato_clock")) var is_starting = false

    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date().addingTimeInterval(60*25), type: .starting)
    }

    func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date().addingTimeInterval(60*25), type: .starting)
        completion(entry)
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        // 因为后台不好刷新，所以只好通过时间线来控制小组件展示样式
//        print("getTimeline")
        var entries: [Entry] = []

        let entry = SimpleEntry(date: tomatoDate, type: .starting)
        let restEntry = SimpleEntry(date: tomatoDate.addingTimeInterval(1), type: .resting)

        entries.append(restEntry)
        if is_starting {
            entries.append(entry)
        }

        let timeline = Timeline(entries: entries, policy: .never)
        completion(timeline)
    }
}

struct SimpleEntry: TimelineEntry {
    let date: Date
    let type: type

    enum type {
        case starting
        case resting
    }
}

struct TomatoClockWidgetEntryView: View {
    // 每次刷新时间线，才会更新此处
    @AppStorage("is_starting", store: UserDefaults(suiteName: "group.com.dale.tomato_clock")) var is_starting = false

    @AppStorage("tomatoDate", store: UserDefaults(suiteName: "group.com.dale.tomato_clock")) var tomatoDate: Date = Date().addingTimeInterval(25*60)

    @AppStorage("sliderValue", store: UserDefaults(suiteName: "group.com.dale.tomato_clock")) var sliderValue: Double = 1

    let timer = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect()

    var entry: Provider.Entry

    var body: some View {
        VStack(alignment: .leading) {
            Spacer()

            switch entry.type {
            case .starting:
                Text(tomatoDate, style: .timer)
                    .font(.largeTitle)
                    .fontWeight(.heavy)
                    .italic()

            case .resting:
                HStack {
                    Text(Int(sliderValue).description)
                        .font(.largeTitle)
                        .fontWeight(.heavy)
                        .italic()
                    Text("mins")
                        .font(.caption)
                        .offset(y: 8)
                        .italic()
                        .bold()
                        .onReceive(timer, perform: { now in
                            // 每秒刷新判断，
                            if now > tomatoDate.addingTimeInterval(1) {
                                // 如果现在超过了tomatoDate
                                is_starting = false

                                // 这也可以测试 is_starting = false 时，会不会持续订阅timer，答案：不会！很好
                                // countOfFinished += 1 // 后期可以设置不同时间 不同番茄数目
                            }
                        })
                }
            }

            Spacer()

            Button(intent: ToggleButtonIntent()) {
                Text("toggle")
            }
        }
    }
}

struct TomatoClockWidget: Widget {
    let kind: String = "TomatoClockWidget"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            if #available(iOS 17.0, *) {
                TomatoClockWidgetEntryView(entry: entry)
                    .containerBackground(.fill.tertiary, for: .widget)

            } else {
                TomatoClockWidgetEntryView(entry: entry)
                    .padding()
                    .background()
            }
        }
        .supportedFamilies([.systemSmall])
        .configurationDisplayName("My Widget")
        .description("This is an example widget.")
    }
}

#Preview(as: .systemSmall) {
    TomatoClockWidget()
} timeline: {
    SimpleEntry(date: .now + 30, type: .starting)
    SimpleEntry(date: .now + 5, type: .resting)
}
